﻿using Consul;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;

namespace CQIE.JonJack.UtilitySource
{
    // 定义服务配置类
    public class ServiceConfig
    {
        public string APIAddress { get; set; }
        public int APIPort { get; set; }
        public string APIName { get; set; }
        public string APICheckAddress { get; set; }
    }

    public static class ConsulConfiguration
    {
        public static void RegisterService(IServiceCollection services,IConfiguration configuration)
        {
            //1.初始化Consul服务信息
            var consulClient = new ConsulClient(opt =>
            {
                opt.Address = new Uri(configuration["ConsulConfig:ConsulServer"]);
                opt.Datacenter = configuration["ConsulConfig:DataCenter"];
            });

            //一直检查Consul，直到注册成功
            while (true)
            {


                if (CheckConsulRunning(consulClient).Result)
                {
                    Console.WriteLine("Console开启成功");
                    break;
                }
                Console.WriteLine("Console开启失败，等待下一此开启");

                // 如果Consul不在运行，等待3秒后再次检查
                Thread.Sleep(TimeSpan.FromSeconds(3));
            }


            // 从配置中获取服务列表
            var serviceConfigurations = configuration.GetSection("ConsulConfig:Services").Get<List<ServiceConfig>>();
            //循环注册所有服务
            foreach (var serviceConfig in serviceConfigurations)
            {
                Console.WriteLine(serviceConfig.APICheckAddress);
                // 读取配置信息
                var ip = serviceConfig.APIAddress;
                var port = serviceConfig.APIPort;
                var name = serviceConfig.APIName;
                var healthCheck = serviceConfig.APICheckAddress;

                // 定义注册服务的信息
                var registration = new AgentServiceRegistration()
                {
                    ID = $"{name}-{Guid.NewGuid()}",
                    Name = name,
                    Address = ip,
                    Port = port,
                    //定期健康检查
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(1222),
                        HTTP = $"https://{ip}:{port}/{healthCheck}",
                        Timeout = TimeSpan.FromSeconds(5),//最大超时时间
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10)//超过10秒注销
                    }
                };

                // 注册服务
                consulClient.Agent.ServiceRegister(registration).Wait();
            }
        }

        //Consul检查方法
        private static async Task<bool> CheckConsulRunning(ConsulClient consulClient)
        {
            try
            {
                // 尝试获取Consul的状态
                var leaderStatus = await consulClient.Status.Leader();

                return !string.IsNullOrEmpty(leaderStatus);
            }
            catch
            {
                // 如果连接失败，返回false
                return false;
            }
        }
    }


}
